//
//  AppDelegate+AppUpdate.m
//  TBRentClient
//
//  Created by tonbright on 2018/4/25.
//  Copyright © 2018年 tonbright. All rights reserved.
//

#import "AppDelegate+AppUpdate.h"
#import <AFNetworking.h>
#import "NSString+Rect.h"
#import "NetWorkRequest.h"

@implementation AppDelegate (AppUpdate)


//检查新版本
- (void)checkNewEdition {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    __weak typeof(self) weakSelf = self;
    [manager GET:[NSString stringWithFormat:@"%@%@",Port,Get_Edition] parameters:@{@"SystemType":@"IOS"} progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if ([responseObject[@"Status"] integerValue] == 200) {
            //获取本地和网络版本
            NSString * version = responseObject[@"Content"][@"version"];
            NSString *localVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
            if ([version compareVersion:localVersion] == NSOrderedDescending) {
                [strongSelf remindUpdate:responseObject[@"Content"]];
            }
        } else {
            [[BONoticeBar defaultBar] setNoticeText:responseObject[@"Msg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [NetWorkRequest afnetWorkingErrorMessge:error];
    }];
    
}

/**
 *  有新版本,提醒更新
 */
- (void)remindUpdate:(NSDictionary *)updateInfo
{
    NSString *title;
    NSString *message;
    title = [NSString stringWithFormat:@"检测到新版本 v%@", updateInfo[@"version"]];
    message = [NSString stringWithFormat:@"更新日志: %@", updateInfo[@"updateLog"]];
    NSString *is_update = updateInfo[@"is_update"];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    NSString *appStoreLink = [NSString stringWithFormat:@"http://itunes.apple.com/cn/app/id%@", APPLEID];
    appStoreLink = updateInfo[@"downloadUrl"];
    UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"前往更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appStoreLink]];
        exit(0);
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:updateAction];
    // MARK: -  如果是真的话代表不强制更新----------------
    if ([[HelpObject changeNull:is_update] isEqualToString:@"1"]) {
        [alertController addAction:cancleAction];
    }
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
}

@end
